/**
 * 
 */
package com.edocbase.desktop.plugins.driver;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.draw2d.ActionEvent;
import org.eclipse.draw2d.ActionListener;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.GridLayout;
import org.eclipse.jface.viewers.LabelProvider;

import com.edocbase.biz.diary.entities.WebAccount;
import com.edocbase.desktop.lightweight.ui.LookAndFeel;
import com.edocbase.desktop.plugins.mdiary.ColorBackgroundBorder;

public class WebAccountExplorer extends Figure implements ActionListener {
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger
		.getLogger(WebAccountExplorer.class);
	private List<WebAccount> input = null;
	private WebAccountFigure selected = null;
	LabelProvider labelProvider = null;
	public WebAccountExplorer() {
		super();
		GridLayout glayout =new GridLayout(2, true);
		setLayoutManager(glayout);
		labelProvider = new WebAccountLabelProvider();
		setBorder(new ColorBackgroundBorder(LookAndFeel.white));
	}

	@SuppressWarnings("unchecked")
	public void setInput(List<WebAccount> input){
		this.input = input;
		List children = getChildren();
		for (int i=0;i<children.size();i++){
			WebAccountFigure waf = (WebAccountFigure)children.get(i);
			waf.removeActionListener(this);
		}
		removeAll();
		for (WebAccount act:input){
			WebAccountFigure actFigure = new WebAccountFigure(act);
			actFigure.addActionListener(this);
			actFigure.setIcon(labelProvider.getImage(act));
			actFigure.setText(labelProvider.getText(act));
			add(actFigure);
			if (logger.isDebugEnabled()) {
				logger.debug("" + act);
			}
		}
	}
	public List<WebAccount> getSelectedAccounts(){
		List<WebAccount> actList = new ArrayList<WebAccount>();
		
		List children = getChildren();
		for (int i=0;i<children.size();i++){
			WebAccountFigure waf = (WebAccountFigure)children.get(i);
			if (waf.isSelected()){
				actList.add(waf.getAccount());
			}
		}
		
		return actList;
	}
	public WebAccountFigure getSelected() {
		return selected;
	}

	public void addActionListener(ActionListener l){
		addListener(ActionListener.class, l);
	}
	@Override
	public void actionPerformed(ActionEvent event) {
		if (logger.isDebugEnabled()) {
			logger.debug("" + event);
		}
		selected = (WebAccountFigure) event.getSource();
		Iterator<ActionListener> lsterIterator = getListeners(ActionListener.class);
		for (;lsterIterator.hasNext();){
			ActionListener actListenr = lsterIterator.next();
			actListenr.actionPerformed(event);
		}
	}
}
